1. Add Todo
//todos Reducer
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
id: action.id,
text: action.text,
completed: false
}
];
default:
return state;
}
};
// 测试 addTodo
const testAddTodo = () => {
const stateBefore = [];
const action = {
type: 'ADD_TODO',
id: 0,
text: 'Learn Redux'
};
const stateAfter = [
{
id: 0,
text: 'Learn Redux',
completed: false
}
];
deepFreeze(stateBefore);
deepFreeze(action);
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
testAddTodo();
console.log('Test passed All.')
2. Toggle Todo
//todos Reducer
const todos = (state = [], action) => {
switch (action.type) {
case 'TOGGLE_TODO':
return state.map(todo => {
if (todo.id !== action.id) {
return todo;
}
return {
...todo,
completed: !todo.completed
};
});
default:
return state;
}
};
// 测试 testToggleTodo
const testToggleTodo = () => {
const stateBefore = [
{
id: 0,
text: 'Learn Redux',
completed: false
},
{
id: 1,
text: 'Go Shopping',
completed: false
}
];
const action = {
type: 'TOGGLE_TODO',
id: 1
};
const stateAfter = [
{
id: 0,
text: 'Learn Redux',
completed: false
},
{
id: 1,
text: 'Go Shopping',
completed: true
}
];
deepFreeze(stateBefore);
deepFreeze(action);
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
testToggleTodo();
console.log('Test passed All.')
//最终代码:http://jsbin.com/sunuwed/2/edit?html,js,output